package cn.skillith.showcompanybackend.mapper;

import cn.skillith.showcompanybackend.entity.DeviceLimit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Optional;

@Repository
public interface DeviceLimitMapper extends JpaRepository<DeviceLimit, Long> {
    
    Optional<DeviceLimit> findByDeviceFingerprint(String deviceFingerprint);
    
    @Modifying
    @Transactional
    @Query("UPDATE DeviceLimit d SET d.dailyCount = :count, d.lastResetDate = :date WHERE d.deviceFingerprint = :fingerprint")
    void updateDailyCount(@Param("fingerprint") String deviceFingerprint, 
                         @Param("count") Integer count, 
                         @Param("date") LocalDate date);
    
    @Modifying
    @Transactional
    @Query("UPDATE DeviceLimit d SET d.dailyCount = d.dailyCount + 1, d.totalCount = d.totalCount + 1 WHERE d.deviceFingerprint = :fingerprint")
    void incrementCount(@Param("fingerprint") String deviceFingerprint);
    
    @Modifying
    @Transactional
    @Query("UPDATE DeviceLimit d SET d.isBlocked = :blocked, d.blockedUntil = :blockedUntil WHERE d.deviceFingerprint = :fingerprint")
    void updateBlockStatus(@Param("fingerprint") String deviceFingerprint, 
                          @Param("blocked") Boolean blocked, 
                          @Param("blockedUntil") String blockedUntil);
}